package com.wcj.springboot.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.wcj.springboot.common.Result;
import com.wcj.springboot.controller.dto.UserDTO;
import com.wcj.springboot.utils.TokenUtils;
import org.apache.tomcat.jni.Multicast;
import org.springframework.web.bind.annotation.PathVariable;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.wcj.springboot.service.IUserService;
import com.wcj.springboot.entity.User;


import org.springframework.web.bind.annotation.*;


import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wcj
 * @since 2022-08-16
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private  IUserService userService;

    @GetMapping("/username/{username}")
    public Result getPerson(@PathVariable String username){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        return Result.success(userService.getOne(queryWrapper));
    }

    @PostMapping("/register")
    public Result register(@RequestBody UserDTO userDTO){
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        if(StrUtil.isBlank(username)||StrUtil.isBlank(password)){
            return Result.error("400","参数错误");
        }
        return Result.success(userService.register(userDTO));
    }


    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO){
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        if(StrUtil.isBlank(username)||StrUtil.isBlank(password)){
            return Result.error("400","账号密码错误");
        }
        return Result.success(userService.login(userDTO));
    }


    @PostMapping
    public Result saveOrUpdate(@RequestBody User user){
        return Result.success(userService.saveOrUpdate(user));
    }

    @DeleteMapping("/{id}")
    public Result removeById(@PathVariable Integer id){
        return Result.success(userService.removeById(id));
    }

    @PostMapping("/del/batch")
    public Result removeBatchByIds(@RequestBody List<Integer> ids){
        return Result.success(userService.removeBatchByIds(ids));
    }

    @GetMapping
    public List getList(){
        return userService.list();
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        return Result.success(userService.getById(id));
    }

    @GetMapping("/page")
    public  Result getPage(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize,
                                @RequestParam(defaultValue = "") String username,
                                @RequestParam(defaultValue = "") String email,
                                @RequestParam(defaultValue = "") String address){
            IPage<User> page = new Page<>(pageNum, pageSize);
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            if(!"".equals(username)){
            queryWrapper.like("username",username);
            }
            if(!"".equals(email)){
                queryWrapper.like("email",email);
            }
            if(!"".equals(address)){
                queryWrapper.like("address",address);
            }
            queryWrapper.orderByDesc("id");
            return Result.success(userService.page(page,queryWrapper));
   }

   @GetMapping("/export")
   public void excelExport(HttpServletResponse response) throws Exception {
       List<User> list = getList();
       ExcelWriter writer = ExcelUtil.getWriter(true);
//       writer.addHeaderAlias("id", "ID");
//       writer.addHeaderAlias("username", "用户名");
//       writer.addHeaderAlias("password", "密码");
//       writer.addHeaderAlias("nickname", "昵称");
//       writer.addHeaderAlias("email", "邮箱");
//       writer.addHeaderAlias("phone", "电话");
//       writer.addHeaderAlias("address", "地址");
//       writer.addHeaderAlias("createTime", "创建时间");
//       writer.addHeaderAlias("avatarUrl", "头像");
       writer.write(list,true);
       response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
       response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode("用户信息","utf-8")+".xlsx");
       ServletOutputStream out=response.getOutputStream();
       writer.flush(out, true);
       out.close();
       writer.close();
   }
    @PostMapping("/import")
   public Result ExcelImport(MultipartFile file) throws Exception{
       InputStream inputStream = file.getInputStream();
       ExcelReader reader = ExcelUtil.getReader(inputStream);
       List<User> list = reader.readAll(User.class);
        userService.saveBatch(list);
       return Result.success(true);
   }







}

